package com.bjpowernode.powernotify.queue;

import cn.hutool.core.date.DateUtil;
import com.bjpowernode.powernotify.domain.MessageWrapper;
import lombok.Getter;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
@Getter
public class PollingTask implements Delayed,Runnable {

    //消息数据
    private MessageWrapper messageWrapper;

    private long executeTime;

    public PollingTask(){}

    public PollingTask(MessageWrapper messageWrapper){
        this.messageWrapper=messageWrapper;
        executeTime=computeExecuteTime();
    }

    private long computeExecuteTime() {
        Integer notifyTimes = messageWrapper.getNotifyTimes();
        Date lastNotifyDate = messageWrapper.getLastNotifyDate();
        //本次间隔时间
        Map<Integer,Integer> notifyRule = messageWrapper.getNotifyRule();
        Integer second = notifyRule.get(notifyTimes+1);

        long nextNotifyTime = lastNotifyDate.getTime() + second*1000;
        System.out.println("--->第["+notifyTimes+1+"]次任务,执行时间:"+ DateUtil.format(new Date(nextNotifyTime),"yyyy-MM-dd HH:mm:ss"));
        return nextNotifyTime;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        long diff = this.executeTime - System.currentTimeMillis();
        return unit.convert(diff,TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        PollingTask other = (PollingTask) o;
        return Long.compare(this.executeTime, other.executeTime);
    }

    @Override
    public void run() {
        //处理task有关的和商家异步通知的业务逻辑
        System.out.println("run===处理task有关的和商家异步通知的业务逻辑");
    }
}
